<template>
  <div>
    <div class="cusStepBox">
      <template v-for="(item, index) in courseStep">
        <div :key="'step' + index" :class="[
          'item',
          { activeItem: index == stepActive, disabledItem: !item.enable }
        ]" @click="item.enable ? changeStep(index) : $message.warning('该步骤暂不可用，请先完成课程描述保存后再进行下一步')">
          <img :src="item.icon" class="icon" />
          <span :class="[
            'name',
            { activeName: index == stepActive, itemwide: index == 2, disabledName: !item.enable }
          ]">
            {{ item.name }}
          </span>
          <img v-if="item.showCorner" src="@/assets/dash/hot.png" class="corderMark" />
        </div>
        <div v-if="index < courseStep.length - 1" :key="'step_arrow' + index"
          :class="[index == stepActive - 1 ? 'activeArrow' : 'baseArrow']"></div>
      </template>
    </div>
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="120px">
      <template v-if="stepActive == 0">
        <el-card>
          <h3>课程基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程名称" prop="title">
                <el-input maxlength="20" v-model="postForm.title" size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学习时间" prop="dateRange">
                <el-date-picker v-model="postForm.dateRange" size="small" format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始时间"
                  end-placeholder="结束时间" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程分类">
                <dic-catalog-tree v-model="postForm.catId" dic-code="course_catalog" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="必修课程">
                <el-checkbox v-model="postForm.isMust" label="是" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学完积分">
                <el-input-number v-model="postForm.points" :min="0" :max="999999" size="small" />
                <small>学完课程获得积分数量</small>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课程课时">
                <el-input-number v-model="postForm.periods" :min="0" :max="9999" size="small" />
                <tool-tip msg="由课件总时长分钟除以45分钟得到，如总要求学习时长为90分钟，那计算出来则为2课时" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="课程封面">
                <file-upload v-model="postForm.cover" tips="请上传大于2:1的宽图" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="课程内容" prop="content">
                <Tinymce ref="editor" v-model="postForm.content" :height="400" />
              </el-form-item>
            </el-col>
          </el-row>
          <h3>课程开放权限设置</h3>
          <el-radio-group v-model="postForm.openType" size="small">
            <el-radio :label="2">指定部门</el-radio>
            <el-radio :label="3">指定人员</el-radio>
            <el-radio :label="1">完全公开</el-radio>
          </el-radio-group>

          <div style="padding-top: 20px">
            <div v-if="postForm.openType === 1">
              <el-alert title="开放的，任何人都可以参与学习！" type="warning" />
            </div>

            <div v-if="postForm.openType == 2">
              <depart-refs v-model="postForm.deptCodes" />
            </div>

            <div v-if="postForm.openType == 3">
              <user-refs :ref-id="postForm.id || tempId" list-url="/api/course/person/paging"
                join-url="/api/course/person/join" remove-url="/api/course/person/remove" />
            </div>
          </div>
        </el-card>
      </template>

      <el-row v-show="stepActive == 1">
        <el-col>
          <el-card>
            <dir-list ref="point_list" :is-digital-human="stepActive == 2" v-model="postForm.pointList"
              @hasCourseId="setCourseId" @updateList="updatePointList" />
          </el-card>
        </el-col>
      </el-row>

      <el-row v-show="stepActive == 2">
        <el-col>
          <el-card>
            <dir-list2 ref="dir_list" :is-digital-human="stepActive == 2" v-model="postForm.dirList"
              @updateFileList="updateFileList" @hasCourseId="setCourseId" />
          </el-card>
        </el-col>
      </el-row>
      <!-- <template v-if="stepActive == 3">
        <el-card class="kp_card">
          <el-alert
            title="课程学完后，学员可以在课程详情进入考试，而被选择的考试会变成私密状态，不会在其他地方显示！"
            type="success"
            style="margin-bottom: 20px"/> -->
          <!--          <el-form-item label="学完考试">-->
          <!--            <exam-select-->
          <!--              v-model="postForm.refExam"-->
          <!--              :new_val="newVal"-->
          <!--              style="width: 50%" />-->
          <!--            <el-button-->
          <!--              v-loading="lmLoading"-->
          <!--              type="primary"-->
          <!--              style="margin-left: 20px"-->
          <!--              @click="showLargeModelSetQues"-->
          <!--              >大模型出题</el-button-->
          <!--            >-->
          <!--          </el-form-item>
          <iframe style="width: 100%; border: none; height: 800px" :src="examframeUrl" frameborder="0"
            @error="handleIframeError"></iframe>
        </el-card>
      </template> -->

      <template v-if="stepActive == 3">


        <h3>学习防作弊</h3>
        <el-card>
          <el-form-item label="弹窗防呆校验">
            <el-switch v-model="postForm.checkOn" active-color="#13ce66" inactive-color="#ff4949" />
            <span v-if="postForm.checkOn">
              &nbsp;每隔&nbsp;
              <el-input-number v-model="postForm.checkSec" :min="1" :max="99999" label="分钟" size="mini" />
              &nbsp;分钟出验证码，输入正确才可继续学习&nbsp;
            </span>
          </el-form-item>

          <el-form-item label="禁止视频拖动">
            <el-switch v-model="postForm.videoDrag" active-color="#13ce66" inactive-color="#ff4949" />
            开启后，视频只能顺序播放，不能拖动
          </el-form-item>

          <el-form-item label="课件顺序解锁">
            <el-switch v-model="postForm.stepLock" active-color="#13ce66" inactive-color="#ff4949" />
            必须按顺序学习，学完一个课件才能继续学下一个
          </el-form-item>

          <el-form-item label="每日可学时段">
            <time-range-picker v-model="postForm.dayRule" />
          </el-form-item>

          <el-form-item label="每日学时上限">
            <el-input-number v-model="postForm.dayLimit" :min="0" :max="1440" size="mini" />
            <small>单位：分钟，本门课程每日最大累计学时，超出后无法学习</small>
          </el-form-item>

          <el-form-item label="人脸识别学习">
            <el-switch v-model="postForm.faceStart" active-color="#13ce66" inactive-color="#ff4949" />
            <span>&nbsp;每个课件学习前都需要进行人脸识别&nbsp; </span>
          </el-form-item>

          <el-form-item label="摄像头抓拍">
            <el-switch v-model="postForm.faceCam" active-color="#13ce66" inactive-color="#ff4949" />

            <span v-if="postForm.faceCam">&nbsp;学员开始学习后，每&nbsp;
              <el-input-number v-model="postForm.faceInterval" :min="1" :max="30" label="分钟" size="mini" />
              &nbsp;分钟抓拍一张学员照片&nbsp;（仅PC）
            </span>
          </el-form-item>

          <el-form-item v-if="postForm.faceCam" label="人脸二次校验">
            <el-switch v-model="postForm.faceCheck" active-color="#13ce66" inactive-color="#ff4949" />
            对抓拍图片进行人脸识别，如果连续识别失败超过
            <el-input-number v-model="postForm.faceChance" :min="0" :max="99" label="次数" size="mini" />
            次就退出学习（仅PC）
          </el-form-item>
        </el-card>
      </template>

      <!-- <el-row v-if="stepActive==5">
        <el-col>
          <h3>直播日程  <div style="line-height: 32px; font-size: 14px; color: #ff3333; float: right"><a href="https://obsproject.com/zh-cn/download" target="_blank">直播推荐使用OBS进行推流，点此下载</a></div></h3>

          <el-card>
            <live-list v-model="postForm.liveList" />
          </el-card>
        </el-col>
      </el-row> -->

      <el-row v-if="stepActive == 5">
        <h3>等待学生考试</h3>
      </el-row>

      <el-row v-if="stepActive == 6">
        <div />
      </el-row>
      <div style="margin-top: 20px">
        <!-- v-if="stepActive>=courseStep.length-3" -->
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button plain type="danger" @click="onCancel">返回</el-button>

        <!-- <el-button :disabled="stepActive==0" type="primary" plain style="margin-left: 30px;" @click="preStep">上一步</el-button>
        <el-button :disabled="stepActive==courseStep.length-1" type="primary" plain @click="nextStep">下一步</el-button> -->
      </div>
    </el-form>

    <el-dialog :visible.sync="largeModeQuesVis" :close-on-click-modal="false" :before-close="closeLargeModelSetQues"
      title="大模型自动出题" width="80%" style="min-width: 800px">
      <iframe :height="windowHeight * 0.8" :src="iframeUrl" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import { uuid } from "vue-uuid";
import { fetchDetail, saveData, saveDataGetId, getLMExtrState } from "@/api/course/course";
import DicCatalogTree from "@/components/DicTreeSelect";
import Tinymce from "@/components/Tinymce";
import FileUpload from "@/components/FileUpload";
import UserRefs from "@/components/UserRefs";
import DepartRefs from "@/components/DepartRefs";
import LiveList from "@/views/admin/course/live";
import DirList2 from "@/views/admin/course/file/dir2";
import DirList from "@/views/admin/course/file/dir";
import TimeRangePicker from "@/components/TimeRangePicker";
import ToolTip from "@/components/ToolTip";
import ExamSelect from "@/components/ExamSelect";
import { isDateRange } from "@/utils/validate";
import { mapGetters } from "vuex";
import step_1 from "@/assets/course/step_1.png";
import step_2 from "@/assets/course/step_2.png";
import step_3 from "@/assets/course/step_3.png";
import step_4 from "@/assets/course/step_4.png";
import step_5 from "@/assets/course/step_5.png";
import step_6 from "@/assets/course/step_6.png";
import step_7 from "@/assets/course/step_7.png";
import moment from "moment";
export default {
  components: {
    ExamSelect,
    ToolTip,
    TimeRangePicker,
    DirList,
    DirList2,
    LiveList,
    DepartRefs,
    UserRefs,
    FileUpload,
    Tinymce,
    DicCatalogTree,
  },
  data() {
    return {
      tempId: `temp_${uuid.v4()}`,
      dialogVisible: false,
      excludes: [],
      curIndex: 0,
      postForm: {
        title: "",
        content: "",
        catId: "",
        checkOn: false,
        checkSec: 0,
        faceCam: false,
        videoDrag: false,
        stepLock: false,
        faceStart: false,
        faceCheck: false,
        periods: 0,
        isMust: false,
        openType: 2,
        price: 0,
        points: 0,
        dirList: [],
        pointList: [],
        personList: [],
        liveList: [],
        dateRange: ["", ""],
        dayLimit: 0,
        cover: "",
        dayRule: "",
        deptCodes: [this.$store.getters.deptCode],
        faceChance: 0,
        faceInterval: 0,
        refExam: "",
      },
      tableData: [
        { title: "默认文件夹", fileList: [{ title: "第一个文件夹", fileType: "视频文件" }] },
      ],
      loading: false,
      rules: {
        title: [{ required: true, message: "课程名称不能为空！" }],
        content: [{ required: true, message: "课程描述不能为空！" }],
        dateRange: [{ required: true, validator: isDateRange }],
      },
      largeModeQuesVis: false,
      windowHeight:
        window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
      iframeBaseUrl: "",
      iframeUrl: "",
      examframeUrl: "",
      newVal: null,
      courseStep: [
        { name: "课程描述", icon: step_1, enable: true },
        { name: "知识点抽取", icon: step_2, showCorner: true, enable: false },
        { name: "添加数字人课程", icon: step_3, showCorner: true, enable: false },
        // { name: "出题组卷", icon: step_4, showCorner: true, enable: false },
        { name: "其他配置", icon: step_5, enable: false },
        // { name: "自动阅卷", icon: step_6, showCorner: true },
        // { name: "考试分析", icon: step_7, showCorner: true },
      ],
      stepActive: 0,
      lmLoading: false,
    };
  },

  computed: {
    ...mapGetters(["siteData", "zlBaseUrl"]),
  },

  created() {
    this.iframeBaseUrl = `${this.zlBaseUrl}/#/navigation/page2`;
    if (!this.postForm.dateRange[0]) {
      this.postForm.dateRange[0] = moment(new Date()).format("YYYY-MM-DD") + " 00:00:00";
      this.postForm.dateRange[1] =
        moment(new Date()).add(1, "M").format("YYYY-MM-DD") + " 00:00:00";
    }
    const id = this.$route.params.id;

    if (id !== undefined) {
      this.fetchData(id);
    }
    this.examframeUrl = `${this.iframeBaseUrl}?courseId=${this.$route.params.id}&courseName=${this.postForm.title
      }&time=${new Date().getTime()}`;
  },
  mounted() {

    const value = sessionStorage.getItem("stepActive");
    if (value) {
      this.stepActive = value;
    }

    window.addEventListener("message", (res) => {
      if (res.data && res.data instanceof Object) {
        if (res.data.id && res.data.title) {
          this.newVal = res.data;
        }
        if (res.data.extrCont) {
          this.$refs.point_list.batchAddDir(res.data.extrCont);
        }
        if (res.data.closeIframe) {
          this.closeLargeModelSetQues();
        }
      }
    });
    this.$refs.point_list.postForm = this.postForm;
    // 用于判断是否是当前新创建的课程，若为新创建，则无法从url中获取课程id，此时禁用后面的步骤
    this.getCourseIdFromUrl();
  },
  watch: {
    postForm: {
      handler(newVal, oldVal) {
        this.$nextTick(() => {
          console.log("postForm changed (after DOM update):", newVal);
          sessionStorage.setItem("postForm", JSON.stringify(newVal));
        });
      },
      deep: true, // 深度监听，确保能够检测到数组内部的变化
    },
    stepActive: {
      handler(newVal, oldVal) {
        console.log("stepActive changed:", newVal);
        sessionStorage.setItem("stepActive", newVal);
      },
      deep: true, // 深度监听，确保能够检测到数组内部的变化
      immediate: false, // 是否在初始化时立即执行一次监听器
    },
    // 监听 postForm.dirList 的变化

    "postForm.pointList": {
      handler(newVal, oldVal) {
        console.log("postForm.pointList changed:", newVal);
        // 在这里执行你希望的逻辑
      },
      deep: true, // 深度监听，确保能够检测到数组内部的变化
      immediate: false, // 是否在初始化时立即执行一次监听器
    },
  },
  methods: {
    getCourseIdFromUrl() {
      const url = window.location.href;
      const match = url.match(/\/update\/(\d+)/);
      if (match && match[1]) {
        this.courseStep = this.courseStep.map((item, index) => {
          if (index > 0) {
            item.enable = true;
          }
          return item;
        });
      } else {
        this.stepActive = 0;
      }
    },
    handleIframeError() {
      this.$message("页面加载失败，请刷新重试");
    },
    nextStep() {
      try {
        if (this.stepActive == 0) {
          if (!this.postForm.title) {
            throw new Error("请输入课程名称");
          }
          if (!this.postForm.dateRange[0]) {
            throw new Error("请选择学习时间");
          }
          if (!this.postForm.content) {
            throw new Error("请输入课程内容");
          }
        }

        if (this.stepActive == 1) {
          if (this.$refs.point_list.pointList.length <= 0) {
            throw new Error("请先进行知识点抽取");
          }
        }
        this.stepActive = ++this.stepActive;
        if (this.stepActive == 2) {
          window.scrollTo({
            top: 0,
            // behavior: 'smooth'
          });
        }
      } catch (msg) {
        this.$message.error(msg);
      }
    },
    preStep() {
      this.stepActive = --this.stepActive;
      if (this.stepActive == 1) {
        window.scrollTo({
          top: 0,
          // behavior: 'smooth'
        });
      }
    },

    changeStep(index) {
      this.stepActive = index;
    },
    setCourseId(id) {
      this.postForm.id = id;
    },
    getDirCount() {
      let count = 0;
      this.$refs.dir_list.dirList.map((item) => {
        if (item.fileList.length > 0) {
          ++count;
        }
      });
      return count;
    },
    showLargeModelSetQues() {
      this.$refs.postForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        if (this.$refs.point_list.pointList.length <= 0) {
          this.$message.error("请先进行知识点抽取");
          return;
        }
        // if (this.getDirCount() <= 0) {
        //   this.$message.error('请至少选择一个课件')
        //   return
        // }
        this.lmLoading = true;
        const courseRes = await this.getCourseId();
        if (courseRes) {
          try {
            const extrState = await getLMExtrState({ course_id: this.postForm.id });
            this.lmLoading = false;
            if (extrState.status) {
              this.iframeUrl = `${this.iframeBaseUrl}?courseId=${this.postForm.id}&courseName=${this.postForm.title
                }&time=${new Date().getTime()}`;
              this.largeModeQuesVis = true;
            } else {
              this.$message.error(extrState.msg);
            }
          } catch (err) {
            this.lmLoading = false;
          }
        }
      });
    },
    updatePointList(newList) {
      console.log(newList);
      this.postForm.pointList = newList;
    },
    updateFileList(newList) {
      this.postForm.dirList = newList;
    },
    async getCourseId() {
      // 赋值临时
      if (!this.postForm.id) {
        this.postForm.id = this.tempId;

        // 时间段覆盖
        this.postForm.startTime = this.postForm.dateRange[0];
        this.postForm.endTime = this.postForm.dateRange[1];
        // 先保存课程，获取课程id
        try {
          const courseRes = await saveDataGetId(this.postForm);
          if (courseRes.data) {
            this.postForm.id = courseRes.data;
            this.$refs.point_list.postForm = this.postForm;
            return true;
          } else {
            this.$message.error("课程保存失败，请重试");
            this.lmLoading = false;
            return false;
          }
        } catch (err) {
          this.lmLoading = false;
        }
      } else {
        return true;
      }
    },
    closeLargeModelSetQues() {
      this.largeModeQuesVis = false;
    },
    fetchData(id) {
      //   const postFormvalue = sessionStorage.getItem('postForm');
      // if(postFormvalue){
      //   this.postForm=JSON.parse(postFormvalue)
      //   this.$refs.point_list.postForm=JSON.parse(postFormvalue)
      //   return
      // }
      fetchDetail(id).then((res) => {
        const data = res.data;
        // 合并赋值
        Object.assign(this.postForm, data);

        // 起始时间
        if (data.startTime && data.endTime) {
          this.postForm.dateRange = [data.startTime, data.endTime];
        }
        this.$refs.editor.setContent(this.postForm.content);
      });
    },
    submitForm() {
      try {
        if (!this.postForm.title) {
          throw new Error("请输入课程名称");
        }
        if (!this.postForm.dateRange[0]) {
          throw new Error("请选择学习时间");
        }
        if (!this.postForm.content) {
          throw new Error("请输入课程内容");
        }

        // 赋值临时
        if (!this.postForm.id) {
          this.postForm.id = this.tempId;
        }
        // 时间段覆盖
        this.postForm.startTime = this.postForm.dateRange[0];
        this.postForm.endTime = this.postForm.dateRange[1];

        this.$refs.postForm.validate((valid) => {
          if (!valid) {
            return;
          }

          saveData(this.postForm).then(() => {
            this.$notify({
              title: "成功",
              message: "课程保存成功！",
              type: "success",
              duration: 2000,
            });

            this.$router.push({ name: "ListCourse" });
          });
        });
      } catch (msg) {
        this.$message.error(msg);
      }
    },

    onCancel() {
      this.$router.back();
      // this.$router.push({ name: 'ListCourse' })
    },
  },
};
</script>
<style scoped lang="scss">
.kp_card {

  ::v-deep .el-form-item__content,
  .el-form-item__content::before,
  .el-form-item__content::after {
    display: flex !important;
  }

  /deep/.el-button--primary {
    position: relative;
  }

  /deep/.el-button--primary::before {
    content: "";
    width: 60px;
    height: 18px;
    background: url("../../../assets/exam/corner_mark.png") no-repeat;
    background-size: 100% 100%;
    position: absolute;
    top: -40%;
    right: -40%;
    z-index: 1000;
  }
}

.cusStepBox {
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: auto;
  overflow-x: auto;
  padding: 0 25px 0 5px;
  box-sizing: border-box;

  .item {
    min-width: 130px;
    height: 48px;
    border-radius: 25px;
    box-shadow: #c2c2c2 0 0 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    cursor: pointer;

    .icon {
      width: 18px;
      height: 18px;
      margin-right: 8px;
      object-fit: contain;
    }

    .name {
      font-size: 15px;
      color: #606266;
    }

    .activeName {
      color: #1c1d1e;
    }

    .itemwide {
      font-size: 13px;
      font-weight: bold;
    }

    .corderMark {
      width: 55px;
      height: 55px;
      position: absolute;
      top: -30px;
      right: -25px;
    }
  }

  .activeItem {
    border: 2px solid #1890ff;
  }

  .disabledItem {
    opacity: 0.5;
    cursor: not-allowed;
    background-color: #f5f5f5;
    box-shadow: none;
  }

  .disabledName {
    color: #aaa;
  }

  .baseArrow,
  .activeArrow {
    min-width: 45px;
    width: calc(100% - 910px);
    height: 1px;
    background: #cccccc;
    margin-left: 15px;
    margin-right: 15px;
    position: relative;
  }

  .activeArrow {
    height: 2px;
    background: #1890ff;
  }

  .baseArrow::after,
  .activeArrow::after {
    content: "";
    position: absolute;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
    border-left: 12px solid #cccccc;
    border-top: 6px solid transparent;
    border-bottom: 6px solid transparent;
  }

  .activeArrow::after {
    border-left: 14px solid #1890ff;
    border-top: 7px solid transparent;
    border-bottom: 7px solid transparent;
  }
}
</style>
